package com.lzf.aspect;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lzf.domain.dto.ErrorCode;
import com.lzf.domain.dto.ReturnValue;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.stereotype.Component;

/**
 * token返回json 切面
 */
@Component
@Aspect
@Slf4j
public class AuthTokenAspect {
    @Autowired
    private ObjectMapper mapper;

    @Around("execution(* org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.postAccessToken(..))")
    public Object handleControllerMethod(ProceedingJoinPoint pjp) throws Throwable {
        Object proceed = null;
        try {
            proceed = pjp.proceed();
        } catch (Throwable throwable) {
            throw throwable;
        }
        HttpHeaders headers = new HttpHeaders();
        headers.set("Cache-Control", "no-store");
        headers.set("Pragma", "no-cache");
        headers.set("Content-Type", "application/json;charset=UTF-8");

        if(proceed == null) {
            return ResponseEntity.status(200).headers(headers).body(mapper.writeValueAsString(new ReturnValue<String>(ErrorCode.ERROR_USER_PASSWORD)));
        }

        ResponseEntity<OAuth2AccessToken> responseEntity = (ResponseEntity<OAuth2AccessToken>)proceed;
        if (responseEntity.getStatusCode().is2xxSuccessful()) {
            return ResponseEntity.status(200).headers(headers).body(mapper.writeValueAsString(new ReturnValue<OAuth2AccessToken>(responseEntity.getBody())));
        } else {
            return ResponseEntity.status(200).headers(headers).body(mapper.writeValueAsString(new ReturnValue<String>(ErrorCode.ERROR_USER_PASSWORD)));
        }
    }

}